//  1. 使用Promise.race  在promise完成前，使用别的promise的完成状态打断它的返回
//  Promise.race 只要有一个 promise 的状态发生了变化，不管是 resolve 还是 reject 都会忽略掉其他的 promise 的结果。
function abortPromise(asyncFuc: () => Promise<any>) {
  let controller = new AbortController();
  return {
    run: () =>
      new Promise((resolve, reject) => {
        const task = asyncFuc();
        const abortPromise = new Promise((_, rejectAbort) => {
          controller.signal.addEventListener("abort", () => {
            rejectAbort(new Error("Promise aborted"));
          });
        });

        Promise.race([task, abortPromise]).then(resolve).catch(reject);
      }),
    abort() {
      controller.abort();
    },
  };
}
type TaskFunction = () => Promise<any>;
interface QueueItem {
  task: TaskFunction;
  retry: number;
}
// 优化队列并发添加重试机制
function handQueue(limit = 6, maxRetry = 3) {
  let current = 0;
  const queue: QueueItem[] = [];

  function dequeue() {
    while (queue.length && current < limit) {
      current++;
      const item = queue.shift();
      if (!item) continue;

      const { task, retry } = item;
      if (retry > maxRetry) {
        current--;
        continue;
      }

      task()
        .catch((error) => {
          queue.push({ task, retry: retry + 1 });
          console.error("Request failed:", error);
        })
        .finally(() => {
          current--;
          dequeue();
        });
    }
  }

  return (task: TaskFunction) => {
    queue.push({ task, retry: 0 });
    dequeue();
  };
}
